package com.eiokey.linkbus.message;


import androidx.lifecycle.LifecycleOwner;

import com.eiokey.linkbus.annotation.LinkBusAnnotationHandler;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * description  通过继承此接口，实现事件注册
 * use
 * param
 * return
 * @author JetQiao
 * @date 2021/7/23  13:31
 */

public interface LinkArcEventBusListener {
    /**
     * 初始化，注册到事件总线
     * @param lifecycleOwner
     */
    default void injectBus(LifecycleOwner lifecycleOwner) {
        Method[] methods = lifecycleOwner.getClass().getDeclaredMethods();
        if (methods.length == 0) {
            return;
        }
        List<Method> allMethods = new ArrayList<>(Arrays.asList(methods));
        if (lifecycleOwner.getClass().getSuperclass() != null) {
            Method[] superMethods = lifecycleOwner.getClass().getSuperclass().getDeclaredMethods();
            if (superMethods.length != 0) {
                allMethods.addAll(Arrays.asList(superMethods));
            }
        }
        LinkBusAnnotationHandler handler = new LinkBusAnnotationHandler();
        for (Method method : allMethods) {

            Annotation[] annotations = method.getAnnotations();
            if (annotations.length == 0) {
                continue;
            }

            for (Annotation annotation : annotations) {
                handler.collectMethodAnnotation(method, annotation);
            }
        }
        handler.handleMethodAnnotation(lifecycleOwner);
    }
}

